﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using EzPos.Model.Supplier;
using EzPos.Properties;
using EzPos.Service;
using EzPos.Service.Common;
using EzPos.Service.Supplier;

namespace EzPos.GUIs.Forms
{
    public partial class FrmSupplier : Form
    {
        private CommonService _commonService;
        private Supplier _supplier;
        private SupplierService _supplierService;
        private bool _isModified;

        public FrmSupplier()
        {
            InitializeComponent();
        }

        public Supplier Supplier
        {
            get { return _supplier; }
            set { _supplier = value; }
        }

        public SupplierService SupplierService
        {
            get { return _supplierService; }
            set { _supplierService = value; }
        }

        public CommonService CommonService
        {
            get { return _commonService; }
            set { _commonService = value; }
        }

        private void SetModifydStatus(bool modifyStatus)
        {
            _isModified = modifyStatus;
            btnSave.Enabled = modifyStatus;
        }

        private void ModificationHandler(object sender, EventArgs e)
        {
            SetModifydStatus(true);
        }

        private void CmbCountryEnter(object sender, EventArgs e)
        {
            cmbCountry.SelectedIndexChanged += ModificationHandler;
        }

        private void CmbCountryLeave(object sender, EventArgs e)
        {
            cmbCountry.SelectedIndexChanged -= ModificationHandler;
            cmbCountry.TextChanged -= ModificationHandler;
        }

        private void FrmSupplier_Load(object sender, EventArgs e)
        {
            if (_supplierService == null)
                _supplierService = ServiceFactory.GenerateServiceInstance().GenerateSupplierService();

            if (_commonService == null)
                _commonService = ServiceFactory.GenerateServiceInstance().GenerateCommonService();

            ThreadStart threadStart = UpdateControlContent;
            var thread = new Thread(threadStart);
            thread.Start();
        }

        private void SetSupplierInfo()
        {
            if (_supplier == null)
                return;

            try
            {
                txtSupplierName.Text = _supplier.SupplierName;
                txtPhoneNumber.Text = _supplier.PhoneNumber;
                txtFaxNumber.Text = _supplier.FaxNumber;
                txtEmailAddress.Text = _supplier.EmailAddress;
                txtWebsite.Text = _supplier.Website;
                cmbCountry.SelectedValue = _supplier.CountryId;
                txtBankInfo.Text = _supplier.BankInformation;
                txtAddress.Text = _supplier.Address;
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            }
        }

        private void BtnSaveClick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtSupplierName.Text))
                {
                    const string briefMsg = "អំពីពត៌មាន";
                    var detailMsg = Resources.MsgInvalidData;
                    using (var frmMessageBox = new FrmExtendedMessageBox())
                    {
                        frmMessageBox.BriefMsgStr = briefMsg;
                        frmMessageBox.DetailMsgStr = detailMsg;
                        frmMessageBox.IsCanceledOnly = true;
                        frmMessageBox.ShowDialog(this);
                        return;
                    }
                }

                if (cmbCountry.SelectedIndex == -1)
                {
                    const string briefMsg = "អំពីពត៌មាន";
                    var detailMsg = Resources.MsgInvalidData;
                    using (var frmMessageBox = new FrmExtendedMessageBox())
                    {
                        frmMessageBox.BriefMsgStr = briefMsg;
                        frmMessageBox.DetailMsgStr = detailMsg;
                        frmMessageBox.IsCanceledOnly = true;
                        frmMessageBox.ShowDialog(this);
                        return;
                    }
                }

                if (_supplier == null)
                    _supplier = new Supplier();

                _supplier.SupplierName = txtSupplierName.Text;
                _supplier.PhoneNumber = txtPhoneNumber.Text;
                _supplier.FaxNumber = txtFaxNumber.Text;
                _supplier.EmailAddress = txtEmailAddress.Text;
                _supplier.Website = txtWebsite.Text;
                _supplier.CountryId = Int32.Parse(cmbCountry.SelectedValue.ToString());
                _supplier.CountryStr = cmbCountry.Text;
                _supplier.BankInformation = txtBankInfo.Text;
                _supplier.Address = txtAddress.Text;

                _supplierService.SupplierManagement(
                    _supplier,
                    _supplier.SupplierId != 0 ? Resources.OperationRequestUpdate : Resources.OperationRequestInsert);

                DialogResult = DialogResult.OK;
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            }
        }

        private void UpdateControlContent()
        {
            if (_supplierService == null)
                _supplierService = ServiceFactory.GenerateServiceInstance().GenerateSupplierService();

            SafeCrossCallBackDelegate safeCrossCallBackDelegate = null;
            if (cmbCountry.InvokeRequired)
                safeCrossCallBackDelegate = UpdateControlContent;

            if (cmbCountry.InvokeRequired)
                Invoke(safeCrossCallBackDelegate);
            else
            {
                var searchCriteria = new List<string>
                                         {
                                             "ParameterTypeId IN (" + Resources.AppParamCountry + ")"
                                         };
                var objList = _commonService.GetAppParameters(searchCriteria);

                _commonService.PopAppParamExtendedCombobox(
                    ref cmbCountry, objList, int.Parse(Resources.AppParamCountry), true);

                SetSupplierInfo();
                SetModifydStatus(false);
            }
        }

        private void TxtAddressEnter(object sender, EventArgs e)
        {
            txtAddress.TextChanged += ModificationHandler;
        }

        private void TxtAddressLeave(object sender, EventArgs e)
        {
            txtAddress.TextChanged -= ModificationHandler;
        }

        private void FrmSupplier_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ((DialogResult == DialogResult.Cancel) && (_isModified))
            {
                const string briefMsg = "អំពីការបោះបង់";
                var detailMsg = Resources.MsgOperationRequestCancel;
                using (var frmMessageBox = new FrmExtendedMessageBox())
                {
                    frmMessageBox.BriefMsgStr = briefMsg;
                    frmMessageBox.DetailMsgStr = detailMsg;
                    if (frmMessageBox.ShowDialog(this) != DialogResult.OK)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
            }

            if (!_isModified)
            {
                DialogResult = DialogResult.Cancel;
                return;
            }
        }

        private void BtnSaveMouseEnter(object sender, EventArgs e)
        {
            btnSave.BackgroundImage = Resources.background_9;
        }

        private void BtnSaveMouseLeave(object sender, EventArgs e)
        {
            btnSave.BackgroundImage = Resources.background_2;
        }

        private void BtnCancelMouseEnter(object sender, EventArgs e)
        {
            btnCancel.BackgroundImage = Resources.background_9;
        }

        private void BtnCancelMouseLeave(object sender, EventArgs e)
        {
            btnCancel.BackgroundImage = Resources.background_2;
        }

        #region Nested type: SafeCrossCallBackDelegate

        private delegate void SafeCrossCallBackDelegate();

        #endregion

        private void TxtSupplierNameEnter(object sender, EventArgs e)
        {
            txtSupplierName.TextChanged += ModificationHandler;
        }

        private void TxtSupplierNameLeave(object sender, EventArgs e)
        {
            txtSupplierName.TextChanged -= ModificationHandler;
        }

        private void TxtPhoneNumberEnter(object sender, EventArgs e)
        {
            txtPhoneNumber.TextChanged += ModificationHandler;
        }

        private void TxtPhoneNumberLeave(object sender, EventArgs e)
        {
            txtPhoneNumber.TextChanged -= ModificationHandler;
        }

        private void TxtFaxNumberEnter(object sender, EventArgs e)
        {
            txtFaxNumber.TextChanged += ModificationHandler;
        }

        private void TxtFaxNumberLeave(object sender, EventArgs e)
        {
            txtFaxNumber.TextChanged -= ModificationHandler;
        }

        private void TxtEmailAddressEnter(object sender, EventArgs e)
        {
            txtEmailAddress.TextChanged += ModificationHandler;
        }

        private void TxtEmailAddressLeave(object sender, EventArgs e)
        {
            txtEmailAddress.TextChanged -= ModificationHandler;
        }

        private void TxtWebsiteEnter(object sender, EventArgs e)
        {
            txtWebsite.TextChanged += ModificationHandler;
        }

        private void TxtWebsiteLeave(object sender, EventArgs e)
        {
            txtWebsite.TextChanged -= ModificationHandler;
        }

        private void TxtBankInfoEnter(object sender, EventArgs e)
        {
            txtBankInfo.TextChanged += ModificationHandler;
        }

        private void TxtBankInfoLeave(object sender, EventArgs e)
        {
            txtBankInfo.TextChanged -= ModificationHandler;
        }
    }
}